import 'redux.dart';

typedef Future EffectFunction(DvaAction action, ModelEffects effects);
typedef StoreOfState ReducerFuction(StoreOfState<DvaState> state, DvaAction action);
typedef Map<String, StoreOfState> StoreGetStateFunction();
typedef Future DispatchFunction(DvaAction action);

class ModelEffects {
  ModelEffects(this.dispatchOrigin, this.getState, this.namespace);

  /// effects中发送Dva Dispatch消息
  Future dispatch(DvaAction action) async {
    if(action.type.contains('/')) {
      return await this.dispatchOrigin(action);
    } else {
      return await this.dispatchOrigin(DvaAction('$namespace/${action.type}', action.payload));
    }
  }

  /// 获取当前命名空间的State
  DvaState getCurrentState() {
    Map<String, StoreOfState> map = getState();
    return map[namespace]?.getState();
  }

  /// 根据命名空间获取State
  T getStateByKey<T>(String key) {
    Map<String, StoreOfState> map = getState();
    return map[key]?.getState() as T;
  }
  /// 获取RootState
  StoreGetStateFunction getState;
  /// 真实的dispatch函数
  DispatchFunction dispatchOrigin;
  /// 命名空间
  String namespace;
}

 class Model<T> {
  /// 命名空间
  late String namespace;
  /// State
  late StoreOfState<T> state;
  /// 修改直接作用于State
  late Map<String, ReducerFuction> reducers;
  /// 不能直接作用于State，通过调用reducers中的方法修改State，通常用于异步获取数据的处理
  late Map<String, EffectFunction> effects;
}

